package problem1262;

//1262.可被三整除的最大值
//https://leetcode.cn/problems/greatest-sum-divisible-by-three/

class Solution {
    public int maxSumDivThree(int[] nums) {
        int x1 = 0x3f3f3f3f, x2 = 0x3f3f3f3f;
        int y1 = 0x3f3f3f3f, y2 = 0x3f3f3f3f;
        int sum = 0;
        for(int n : nums) {
            sum += n;
            if(n % 3 == 1) {
                if(n < x1) {
                    x2 = x1;
                    x1 = n;
                }else if(n < x2) {
                    x2 = n;
                }
            }else if(n % 3 == 2) {
                if(n < y1) {
                    y2 = y1;
                    y1 = n;
                }else if(n < y2) {
                    y2 = n;
                }
            }
        }

        int ret = sum;
        if(sum % 3 == 1) {
            ret = Math.max(sum-x1, sum-y1-y2);
        }else if(sum % 3 == 2) {
            ret = Math.max(sum-x1-x2, sum-y1);
        }
        return ret;
    }
}

/**
x1,x2: nums中%3=1 的最小值和次小值
x2,x3: nums中%3=2 的最小值和次小值

 */